import React from 'react'
import { LdhFieldSet } from '@biz/PageCompnents'
import {
  LdhButton,
  LdhFormItem,
  LdhInput,
  LdhInputNumber,
  LdhObjListSelect,
  LdhRadioGroup,
  LdhRadio,
} from '@biz/Components'
import GUtils from '@/utils'

import { createAction } from './Action'
import Store from './Store'

import './style.less'
import { Col, Row, Tag, Button } from 'antd'
import { EditOutlined } from '@ant-design/icons'
import BaseDetailPage from '@biz/BaseDetailPage'
import moment from 'moment'

let Config = {}
const prefix = 'user-super-page'
export default class UserSuperPage extends BaseDetailPage {
  constructor(props) {
    super(props)
    this.action = createAction()
    this.store = new Store(props, {}, this.action)
    this.className = prefix
  }
  componentDidMount() {
    super.componentDidMount()
    this.action.getAllVipProductList()
    this.action.getAllCouponList()
    // 设置优惠券发放原因的默认值和发放数量的默认值
    this.form().setFieldsValue({
      couponIssueReason: '美团核验',
      couponQuantity: 1,
    })
    // 记录上次发券成功的状态，用于检测状态变化
    this.lastIssueCouponSuccess = false
  }

  componentWillUnmount() {}

  componentDidUpdate(prevProps, prevState) {
    // 检测发券成功状态变化，成功后清除表单数据
    if (this.state.issueCouponSuccess && !this.lastIssueCouponSuccess) {
      this.clearCouponForm()
      this.lastIssueCouponSuccess = true
    } else if (!this.state.issueCouponSuccess) {
      this.lastIssueCouponSuccess = false
    }
  }

  clearCouponForm() {
    // 清除发券相关表单字段
    this.form().setFieldsValue({
      couponId: undefined,
      couponNotes: '',
      couponQuantity: 1,
      couponIssueReason: '美团核验',
    })
    // 重置发放数量编辑状态
    this.setState({ couponQuantityEditable: false })
  }

  handleChange(field, e) {
    console.log(field, e)
    let newState = {}
    newState[field] = e.target.value.trim()
    this.setState(newState)
  }
  handleSelectChange(field, v) {
    console.log(field, v)
    let newState = {}
    newState[field] = v
    this.setState(newState)
  }

  handleSearch() {
    this.form()
      .validateFields(['phone'])
      .then((vo) => {
        let { phone } = vo
        this.action.getUserInfo(phone)
      })
      .catch((e) => {})
  }

  handleRecharge() {
    this.form()
      .validateFields(['rechargeAmount', 'rechargeNotes'])
      .then((values) => {
        let { user } = this.state
        let { rechargeAmount, rechargeNotes } = values
        let vo = {
          userId: user.id,
          amount: rechargeAmount,
          notes: rechargeNotes,
        }
        this.action.mockRecharge(vo)
      })
      .catch((e) => {})
  }

  handleVip() {
    this.form()
      .validateFields(['vipProductId', 'vipNotes'])
      .then((values) => {
        let { user } = this.state
        let { vipProductId, vipNotes } = values
        let vo = {
          userId: user.id,
          productId: vipProductId,
          notes: vipNotes,
        }
        this.action.mockVip(vo)
      })
      .catch((e) => {})
  }

  handleIssueCoupon() {
    const formValues = this.form().getFieldsValue()
    let { couponIssueReason = '美团核验' } = formValues

    let validateFields = ['couponId', 'couponQuantity']
    if (couponIssueReason === '后台发放') {
      validateFields.push('couponNotes')
    }

    this.form()
      .validateFields(validateFields)
      .then((values) => {
        let { user, couponList = [] } = this.state
        let { couponId, couponNotes, couponQuantity = 1 } = values
        // 获取优惠券名称
        const selectedCoupon = couponList.find(
          (item) => item.value === Number(couponId)
        )
        const couponName = selectedCoupon
          ? selectedCoupon.name || selectedCoupon.label
          : '未知优惠券'

        // 二次确认
        GUtils.confirm(
          '确认发券',
          `确定要向用户 ${user.phone} 发放 ${couponQuantity} 张"${couponName}"吗？`,
          () => {
            // 根据发放原因设置 sourceType: 2-后台发放, 3-美团核销
            const sourceType = couponIssueReason === '后台发放' ? 2 : 3
            let vo = {
              userId: user.id,
              couponId: couponId ? Number(couponId) : null,
              count: couponQuantity || 1,
              issueRemark: couponNotes || '',
              sourceType: sourceType,
            }
            this.action.issueCoupon(vo)
          }
        )
      })
      .catch((e) => {})
  }

  handleCouponIssueReasonChange(e) {
    const reason = e.target.value
    this.setState({ couponIssueReason: reason })
    // 清空备注字段并更新表单值
    this.form().setFieldsValue({
      couponIssueReason: reason,
      couponNotes: '',
    })
  }

  handleToggleCouponQuantityEdit() {
    const { couponQuantityEditable } = this.state
    this.setState({ couponQuantityEditable: !couponQuantityEditable })
    // 如果取消编辑，恢复默认值
    if (couponQuantityEditable) {
      this.form().setFieldsValue({ couponQuantity: 1 })
    }
  }

  renderUserInfo() {
    let {
      user,
      vipProductList = [],
      couponList = [],
      couponIssueReason = '美团核验',
      couponQuantityEditable = false,
    } = this.state
    if (user == null) return <div></div>

    let date = user.vipExpirationEndDate
    if (date) {
      date = moment(date)
    }
    let now = moment.now()
    return (
      <div>
        <LdhFieldSet title="基本信息" className="flex-between">
          <Row gutter={20}>
            <Col span={12}>用户ID：{user.uid}</Col>
            <Col span={12}>用户名：{user.username}</Col>
          </Row>
          <Row gutter={20}>
            <Col span={12}>手机号：{user.phone}</Col>
            <Col span={12}>昵称：{user.phone}</Col>
          </Row>
          <Row gutter={20}>
            <Col span={12}>
              上次登陆：{GUtils.dateTimeFormatter(user.createTime)}
            </Col>
            <Col span={12}>
              上次登陆：{GUtils.dateTimeFormatter(user.lastLoginTime)}
            </Col>
          </Row>
        </LdhFieldSet>

        <LdhFieldSet title="优惠券发放" className="flex-between">
          <Row gutter={20}>
            <Col span={24}>
              <LdhFormItem label="发放原因" name="couponIssueReason" required>
                <LdhRadioGroup
                  value={couponIssueReason}
                  onChange={this.handleCouponIssueReasonChange.bind(this)}
                >
                  <LdhRadio value="美团核验">美团核验</LdhRadio>
                  <LdhRadio value="后台发放">后台发放</LdhRadio>
                </LdhRadioGroup>
              </LdhFormItem>
            </Col>
          </Row>

          <Row gutter={20}>
            <Col span={6}>
              <LdhFormItem label="发放数量" name="couponQuantity" required>
                <div className="coupon-quantity-wrapper">
                  <LdhInputNumber
                    min={1}
                    precision={0}
                    placeholder="数量"
                    disabled={!couponQuantityEditable}
                    defaultValue={1}
                    style={{ flex: 1 }}
                  />
                  <Button
                    type="link"
                    icon={<EditOutlined />}
                    onClick={this.handleToggleCouponQuantityEdit.bind(this)}
                    className="edit-btn"
                  >
                    {couponQuantityEditable ? '取消' : '编辑'}
                  </Button>
                </div>
              </LdhFormItem>
            </Col>
          </Row>

          <Row gutter={20}>
            <Col span={7}>
              <LdhFormItem label="优惠券" name="couponId" required>
                <LdhObjListSelect
                  list={couponList}
                  placeholder="请选择"
                  className="coupon-select-wide"
                />
              </LdhFormItem>
            </Col>

            <Col span={11}>
              <LdhFormItem
                label="备注信息"
                name="couponNotes"
                required={couponIssueReason === '后台发放'}
              >
                <LdhInput maxLength={255} showCount placeholder="请输入备注" />
              </LdhFormItem>
            </Col>
            <Col span={5}>
              <LdhButton
                type="primary"
                className="mt-40"
                loading={this.state.couponLoading}
                onClick={this.handleIssueCoupon.bind(this)}
              >
                发券
              </LdhButton>
            </Col>
          </Row>
          <span className="tip">
            *
            根据选择优惠券向用户发放,发放数量默认为1张,发放原因为"后台发放"时,备注信息必填。可通过用户优惠券列表查询发券记录
          </span>
        </LdhFieldSet>

        <LdhFieldSet title="余额信息" className="flex-between">
          <Row gutter={20}>
            <Col span={12}>余额：{user.balanceAmount}</Col>
          </Row>
          <Row gutter={20}>
            <Col span={6}>
              <LdhFormItem
                label="充值金额"
                name="rechargeAmount"
                required
                rules={[
                  {
                    pattern: window.CONFIG.REG_NUM_D2_2,
                    message: '金额保留两位小数',
                  },
                ]}
              >
                <LdhInput />
              </LdhFormItem>
            </Col>
            <Col span={12}>
              <LdhFormItem label="备注" name="rechargeNotes" required>
                <LdhInput maxLength={255} showCount placeholder="请输入备注" />
              </LdhFormItem>
            </Col>
            <Col span={6}>
              <LdhButton
                type="primary"
                className="mt-40"
                onClick={this.handleRecharge.bind(this)}
              >
                内部充值
              </LdhButton>
            </Col>
          </Row>
          <span className="tip">
            根据金额创建一个充值订单，单号以“SUPER"开头，支付金额为0；同时用户的余额增加相应的金额
          </span>
        </LdhFieldSet>

        <LdhFieldSet title="会员信息" className="flex-between">
          {!date ? (
            <Row gutter={20}>
              <Col span={12}>会员：非会员</Col>
            </Row>
          ) : (
            <div>
              <Row gutter={20}>
                <Col span={12}>
                  会员：
                  {date.isAfter(now) ? (
                    <Tag color="success">会员</Tag>
                  ) : (
                    <Tag color="error">过期</Tag>
                  )}
                </Col>
                <Col span={12}>
                  产品：
                  <Tag>
                    {user.vipProductName} ({user.vipDays}天)
                  </Tag>
                </Col>
              </Row>
              <Row gutter={20}>
                <Col span={12}>免费时间：{user.vipFreeTime}分钟</Col>
                <Col span={12}>
                  有效期：{GUtils.dateFormatter(user.vipExpirationEndDate)}
                </Col>
              </Row>
            </div>
          )}

          <Row gutter={20}>
            <Col span={6}>
              <LdhFormItem label="会员产品" name="vipProductId" required>
                <LdhObjListSelect list={vipProductList} />
              </LdhFormItem>
            </Col>
            <Col span={12}>
              <LdhFormItem label="备注" name="vipNotes" required>
                <LdhInput maxLength={255} showCount placeholder="请输入备注" />
              </LdhFormItem>
            </Col>
            <Col span={6}>
              <LdhButton
                type="primary"
                className="mt-40"
                onClick={this.handleVip.bind(this)}
              >
                内部会员
              </LdhButton>
            </Col>
          </Row>
          <span className="tip">
            根据选择的会员产品，创建一个充值订单，单号以"SUPER"开头，支付金额为0；用户成为会员，有效期从当天开始算
          </span>
        </LdhFieldSet>
      </div>
    )
  }

  renderDetail() {
    let { loading, detail } = this.state
    return (
      <LdhFieldSet title="内部充值/会员" className="flex-between">
        <Row gutter={20}>
          <Col span={12}>
            <LdhFormItem label="用户手机号" name="phone" required>
              <LdhInput
                maxLength={60}
                showCount
                placeholder="请输入用户手机号"
              />
            </LdhFormItem>
          </Col>
          <Col span={6}>
            <LdhButton
              className="mt-40"
              type="primary"
              loading={loading}
              onClick={this.handleSearch.bind(this)}
            >
              查询
            </LdhButton>
          </Col>
        </Row>
        {this.renderUserInfo()}
      </LdhFieldSet>
    )
  }
}
